<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends CI_Controller {

	

	public function index()
	{
		
		if($this->session->userdata('account_id') != null){
			redirect(base_url().'search');
		}else{
		
			if(isset($_POST['email']) || isset($_POST['password'])){
				$email 	= 	$this->input->post('email');
				$pw 	=	md5($this->input->post('password'));

				$dataArray = $this->verifier_model->verify_login($email,$pw);		

				if(isset($dataArray[0])){
					$this->insertSessionData($dataArray[0]);
				}			

				if(count($dataArray)>0){
					redirect(base_url().'search');
				}else{
					$arrayData = (object) array(
						'error'=>"Either email or password is incorrect",
					);
					$this->load->view('login_view',$arrayData);
				}
			}else{
				$this->load->view('login_view');
			}
		}
		
	}

	public function logout(){
		$this->deleteSessionData();
		redirect(base_url());
	}


	private function insertSessionData($dataArray){
		$sessionData = array(
			'account_id'=> $dataArray['account_id'],
			'username'=> $dataArray['username'],
			'userlevel'=> $dataArray['userlevel']
		);
		$this->session->set_userdata($sessionData);
	}
	private function deleteSessionData(){
		$sessionData = array(
			'account_id'=> '',
			'username'=> '',
			'userlevel'=> ''
		);
		$this->session->unset_userdata($sessionData);
		redirect(base_url());
	}

}
